/**
 * 
 */

package com.tenentia.pcmps.swm.util;

import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

/**
 * @author tEnEntia, S.L.N.E.
 * 
 */
public class DateUtilities {

	/**
	 * 
	 */
	private DateUtilities() {

		super();
	}

	public static int getAge(Date fromDate, Date toDate) {

		GregorianCalendar toGC = new GregorianCalendar();
		toGC.setTime(toDate);
		GregorianCalendar fromGC = new GregorianCalendar();
		fromGC.setTime(fromDate);

		int yearGap = toGC.get(Calendar.YEAR) - fromGC.get(Calendar.YEAR);
		int monthGap = toGC.get(Calendar.MONTH) - fromGC.get(Calendar.MONTH);
		if (monthGap == 0) {
			boolean isFebruary = toGC.get(Calendar.MONTH) == 1;
			int toDayOfMonth = toGC.get(Calendar.DAY_OF_MONTH);
			int fromDayOfMonth = fromGC.get(Calendar.DAY_OF_MONTH);
			if (isFebruary) {
				if (toDayOfMonth == 29) {
					toDayOfMonth = 28;
				}
				if (fromDayOfMonth == 29) {
					fromDayOfMonth = 28;
				}
			}
			int dayGap = toDayOfMonth - fromDayOfMonth;
			if (dayGap < 0) {
				yearGap--;
			}
		} else if (monthGap < 0) {
			yearGap--;
		}
		if (yearGap < 0) {
			yearGap = 0;
		}

		return yearGap;
	}

}
